package com.stars.easyms.datasource.mybatisplus;

import org.springframework.util.ClassUtils;

import static com.stars.easyms.datasource.common.EasyMsDataSourceConstant.*;

/**
 * <p>className: MybatisPlusHelper</p>
 * <p>description: mybatis-plus相关工具类,该类不存在与mybatisPlus的直接调用</p>
 *
 * @author guoguifang
 * @version 1.7.0
 * @date 2020/11/2 11:29 上午
 */
public final class EasyMsMybatisPlusHelper {

    private static Class<?> mybatisPlusBaseMapperClass;

    private static Class<?> mybatisPlusParentMapperClass;

    private static Class<?> mybatisPlusPageInterceptorClass;

    public static boolean hasMybatisPlus() {
        return mybatisPlusBaseMapperClass != null;
    }

    public static boolean isMybatisPlusMapper(Class<?> clazz) {
        if (hasMybatisPlus()) {
            return mybatisPlusBaseMapperClass.isAssignableFrom(clazz)
                    || (mybatisPlusParentMapperClass != null && mybatisPlusParentMapperClass.isAssignableFrom(clazz));
        }
        return false;
    }

    public static Class<?> getMybatisPlusBaseMapperClass() {
        return mybatisPlusParentMapperClass != null ? mybatisPlusParentMapperClass : mybatisPlusBaseMapperClass;
    }

    public static boolean hasMybatisPlusPageInterceptor() {
        return hasMybatisPlus() && mybatisPlusPageInterceptorClass != null;
    }

    public static Class<?> getMybatisPlusPageInterceptorClass() {
        return mybatisPlusPageInterceptorClass;
    }

    static {
        mybatisPlusBaseMapperClass = getClass(MYBATIS_PLUS_BASE_MAPPER_CLASS_NAME);
        mybatisPlusParentMapperClass = getClass(MYBATIS_PLUS_PARENT_MAPPER_CLASS_NAME);
        mybatisPlusPageInterceptorClass = getClass(MYBATIS_PLUS_PAGE_INTERCEPTOR_CLASS_NAME);
    }

    private static Class<?> getClass(String className) {
        try {
            return ClassUtils.forName(className, ClassUtils.getDefaultClassLoader());
        } catch (ClassNotFoundException e) {
            // ignore
        }
        return null;
    }

    private EasyMsMybatisPlusHelper() {
    }
}
